//加载express框架 

const express = require('express');
//导入日期工具类
const moment = require('moment-timezone');
//实例路由 
const router = express.Router();
//导入数据模型 
const { user } = require('../model/db');
const { order } = require('../model/db');
//导入工具类
const { sendEmail,matchCarpoolOrder } = require('../model/utils');
//小程序appID以及AppSecret
const appID = `wxdff4801780968d5d`
const AppSecret = `347d6658b4e7648ece4ede112152bb56`
//导入request库
const request = require('request')
//**************星号内部写API接口******************* */ 
router.get('/wxlogin', async (req, res) => {
    const { code } = req.query
    console.log(code)
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appID}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`
    request(url, (err, response, data) => {
        console.log(response.statusCode)
        if (!err && response.statusCode == 200) {
            //console.log(typeof(data)) 
            res.send({
                status: 'ok',
                openid: JSON.parse(data).openid
            });
        } else {
            console.log(err);
            res.send({
                status: 'err',
                errMsg: err
            })
        }
    })


})
//小程序用户登录，判断用户是否存在，如不存在，则保存用户,如果存在，则读取用户信息 并返回
router.post('/wxGetUserInfo', async (req, res) => {
    try {
        //console.log(req.body)
        const { userInfo } = req.body
        const result = await user.findOne({ openid: userInfo.openid }).select('-_id')
        //console.log(result) 
        if (result) {
            //返回数据库中的结果 
            res.send({ status: 'ok', value: result })
        } else {
            //保存用户
            user.create(userInfo).then((r) => { res.send({ status: 'ok', value: userInfo }) }).catch(res => {
                console.log('插入失败')
            })
        }
    } catch (err) {
        console.log(err)
        res.send({ status: 'err' })
    }
})


//------------上传配置------------------------------ 
//导入multer 
const multer = require('multer')
//上传参数设置 
const storage = multer.diskStorage({
    //配置路径,首先需要创建uploads/images文件夹 
    destination: (req, file, cb) => { cb(null, './uploads/images'); },
    //设置文件名 
    filename: (req, file, cb) => {
        let extName = '.' + file.originalname.split('.').pop();
        let fileName = Date.now() + Math.floor(Math.random() * 10000);
        cb(null, fileName + extName);
    }
})
//应用上传设置，并实例上传对象 
const upload = multer({ storage: storage })
//---------上传配置结束-----------------------------

//头像图片上传 
router.post('/uploadImg', upload.single('img'), (req, res) => {
    try {
        res.send(req.file);
    } catch (error) {
        res.send(error);
        console.log(error)
    }
})
//************************************************* */ 
//用户信息
router.post('/wxUpdateUserInfo', async (req, res) => {
    try {
        const { openid } = req.body
        const result = await user.findOneAndUpdate({ openid }, req.body).select('-_id')
        res.send({
            status: 'success',
        })
    } catch (error) {
        console.log(error)
        res.send({
            status: 'err'
        })
    }
})

//获取手机号：session+code替换手机号
router.post('/wxGetPhoneNumber', async(req,res) => {
    const { code } = req.body;
    // 获取access_token
    getAccessTokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${AppSecret}`
    request(getAccessTokenUrl, (err, response, data) => {
        const {statusCode} = response;
        const {access_token} = JSON.parse(data);
        if (!err && statusCode===200) {
            const getPhoneNumerUrl = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${access_token}`
            request({
                url: getPhoneNumerUrl,
                method: "POST",
                json: true,
                body: {
                    code: code,
                  }
            },(err,response,body) =>{
                const {errcode,errmsg} = body;
                if(err||errcode!=0){
                    res.send({
                        status: 'err',
                        errMsg: errmsg
                    })
                }else{
                    res.send({
                        status: 'success',
                        data: body.phone_info
                    })
                    console.log(body.phone_info.purePhoneNumber)
                }             
            })
        } else {
            console.log(err);
            res.send({
                status: 'err',
                errMsg: err
            })
        }
    })
    
})

//小程序端 申请成为接单员 
router.post('/wxApplyOrder', async (req, res) => {
    try {
        // console.log(req.body) 
        const { openid, personInfo } = req.body
        const result = await user.findOneAndUpdate({ openid }, { personInfo })
        res.send('success')
    } catch (err) {
        console.log(err)
        res.send('fail')
    }
})
//小程序 读取用户申请接单信息 
router.get('/wxGetUser', async (req, res) => {
    try {
        const { openid } = req.query
        const result = await user.findOne({ openid }).select("personInfo")
        res.send({ status: 'success', result })
    } catch (error) { res.send({ status: 'fail' }) }
})
//小程序 管理员读取所有用户接单申请 
router.get('/wxGetAllApply', async (req, res) => {
    try {
        const { page, pageSizes } = req.query;
        const result = await user.find({ personInfo: { $ne: null } }).select("personInfo").skip(page).limit(pageSizes).sort({ "personInfo.applyT ime": -1 }); res.send(result)
    } catch (error) { res.send(error) }
})
//小程序 读取接单申请的记录数 
router.get('/wxApplyCount', async (req, res) => {
    try {
        const count = await user.countDocuments({ personInfo: { $ne: null } });
        res.send({ status: 'success', count })
    } catch (error) {
        res.send({ status: 'error' })
    }
})
//小程序 审核接单申请 
router.post('/wxApplyVerify', async (req, res) => {
    try {
        //console.log(req.body) 
        const { _id, status } = req.body
        if (status === "通过审核") {
            await user.findByIdAndUpdate(_id, { canReceive: true, "personInfo.status": status })
        } else { await user.findByIdAndUpdate(_id, { "personInfo.status": status }) } res.send('success')
    } catch (error) {
        console.log(error)
        res.send('fail')
    }
})
// 保存订单
router.post('/addOrder', async (req, res) => {
    try {
        await order.create(req.body); res.send('success');
    }
    catch (error) {
        res.send('fail'); console.log(error)
    }
})

// 保存拼车订单
router.post('/addCarPoolOrder', async (req, res) => {
    const now = moment();
    let code,message,data={};
    try {
        const orderContent = req.body;
        const {
            startAddress,
            endAddress,
        } = orderContent;
        const {startTime,period} = orderContent.info;

        const isStartEndEqual = startAddress===endAddress;
        const isStartEndSchool = startAddress.slice(0,2)===endAddress.slice(0,2)&&endAddress.slice(0,2)==='学校';
        if(isStartEndEqual||isStartEndSchool){
            message = '走两步就到了'
            code = 'fail'
        } else if (now.isAfter(moment(startTime))){
            message = '出发时间不得早于当前时间'
            code = 'fail'
        } else {
            orderContent.info.endTime = moment(startTime).add(period, 'm').format('YYYY-MM-DD HH:mm')
            message = '提交成功'
            code = 'success'
            const t = await order.create(orderContent);
            await matchCarpoolOrder(t);
        }
        res.send({
            code,
            message
        })

        
    }
    catch (error) {
        message = error;
        res.send({
            code,
            message
        });
        console.log(error)
    }
})

//导出路由 
module.exports = router;